<script setup>
import {
  queryPageApi,
  addApi,
  queryByIdApi,
  updateApi,
  deleteApi,
} from "@/api/dept";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted } from "vue";

// 查询参数
const queryParams = ref({
  name: "",
  status: "",
  page: 1,
  pageSize: 10,
});
// 初始化查询
onMounted(() => {
  search();
});

// 表格数据
const deptList = ref([]);
const total = ref(0);

// 搜索
const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code === 1) {
    deptList.value = result.data.rows;
    total.value = result.data.total;
  }
};
// 对话框
const formTitle = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";
const dept = ref({
  name: "",
  status: "",
});
// 表单校验
const deptFormRef = ref(null);
const rules = ref({
  name: [
    { required: true, message: "部门名称为必填项", trigger: "blur" },
    { min: 2, max: 10, message: "部门名称应该在2-10位之间", trigger: "blur" },
  ],
  status: [{ required: true, message: "部门状态为必填项", trigger: "blur" }],
});
// 添加部门
const handleAdd = () => {
  dialogFormVisible.value = true;
  formTitle.value = "添加部门";
  dept.value = { name: "", status: "" };
  if (deptFormRef.value) {
    deptFormRef.value.resetFields();
  }
};
// 保存部门
const save = async () => {
  deptFormRef.value.validate(async (valid) => {
    //表单true:校验成功  false失败
    if (valid) {
      //校验成功

      let result;
      if (dept.value.id) {
        //如果dept有ID,执行修改--ID有值且不是0就是true,没值或0都是false
        result = await updateApi(dept.value);
      } else {
        result = await addApi(dept.value);
      }

      if (result.code) {
        // 成功
        ElMessage.success("保存成功");
        dialogFormVisible.value = false;
        search();
      } else {
        //失败
        ElMessage.error(result.msg);
      }
    } else {
      ElMessage.error("请填写正确的信息");
    }
  });
};
// 清空
const clear = () => {
  queryParams.value = { name: "", status: "", page: 1, pageSize: 10 };
  search();
};
// 分页大小改变
const handleSizeChange = (val) => {
  search();
};
// 页码改变
const handleCurrentChange = (val) => {
  search();
};
// 点击修改按钮触发
const handleEdit = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code === 1) {
    dialogFormVisible.value = true;
    formTitle.value = "修改部门";
    dept.value = result.data;
    if (deptFormRef.value) {
      deptFormRef.value.resetFields();
    }
  } else {
    ElMessage.error(result.msg);
  }
};
// 删除部门
const handleDelete = async (id) => {
  ElMessageBox.confirm("您确定要删除吗", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const result = await deleteApi(id);
      if (result.code) {
        ElMessage.success("删除成功");
        search();
      } else {
        ElMessage.error(result.msg);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

<template>
  <div class="dept-page">
    <!-- 顶部标题和操作 -->
    <div class="dept-header">
      <div>
        <h2 class="dept-title">
          <el-icon><OfficeBuilding /></el-icon> 部门管理
        </h2>
        <div class="dept-desc">
          高效管理公司各部门，支持新增、编辑、删除和状态切换。
        </div>
      </div>
      <el-button type="primary" @click="handleAdd" class="add-btn" size="large"
        ><el-icon><Plus /></el-icon>添加部门</el-button
      >
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="18" class="dept-stats">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-blue">
          <div class="stat-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">部门总数</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-green">
          <div class="stat-icon">
            <el-icon><CircleCheckFilled /></el-icon>
          </div>
          <div>
            <div class="stat-value">
              {{ deptList.filter((d) => d.status === 1).length }}
            </div>
            <div class="stat-label">正常部门</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-red">
          <div class="stat-icon">
            <el-icon><CircleCloseFilled /></el-icon>
          </div>
          <div>
            <div class="stat-value">
              {{ deptList.filter((d) => d.status === 0).length }}
            </div>
            <div class="stat-label">停用部门</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card stat-yellow">
          <div class="stat-icon">
            <el-icon><Timer /></el-icon>
          </div>
          <div>
            <div class="stat-value">
              {{
                deptList.length > 0
                  ? deptList[0].updateTime?.slice(0, 10)
                  : "--"
              }}
            </div>
            <div class="stat-label">最近更新时间</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 卡片化表格区域 -->
    <el-card class="dept-table-card">
      <template #header>
        <div class="table-header-flex">
          <div class="table-title">
            <el-icon><List /></el-icon> 部门列表
          </div>
          <el-form
            :inline="true"
            :model="queryParams"
            ref="queryForm"
            class="search-form"
          >
            <el-form-item label="部门名称">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入部门名称"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择"
                clearable
                size="small"
                style="width: 120px"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search" size="small"
                ><el-icon><Search /></el-icon>搜索</el-button
              >
              <el-button @click="clear" size="small"
                ><el-icon><Refresh /></el-icon>清空</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table :data="deptList" border stripe class="dept-table" size="small">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="name"
          label="部门名称"
          min-width="160"
          align="center"
        >
          <template #default="scope">
            <el-icon class="dept-table-icon"><OfficeBuilding /></el-icon>
            <span class="dept-name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          min-width="90"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              <el-icon style="vertical-align: middle">
                <template v-if="scope.row.status === 1"
                  ><CircleCheckFilled
                /></template>
                <template v-else><CircleCloseFilled /></template>
              </el-icon>
              {{ scope.row.status === 1 ? "正常" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="最后修改时间"
          min-width="140"
          align="center"
        />
        <el-table-column label="操作" align="center" min-width="120">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row.id)">
              <el-icon><Edit /></el-icon>修改
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row.id)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>

    <!-- 添加/编辑部门对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="formTitle"
      width="420"
      class="dept-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dept"
        :rules="rules"
        ref="deptFormRef"
        label-width="90px"
        class="dept-form"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="dept.name"
            autocomplete="off"
            placeholder="请输入部门名称"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="部门状态" prop="status">
          <el-select v-model="dept.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-page {
  padding: 18px 10px 30px 10px;
  background: #f5f7fa;
  min-height: 100vh;
}
.dept-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 18px;
  gap: 12px;
  flex-wrap: wrap;
}
.dept-title {
  font-size: 28px;
  font-weight: 800;
  background: linear-gradient(90deg, #ff4da6, #ff85c1);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}
.dept-desc {
  color: #909399;
  font-size: 15px;
  margin-bottom: 2px;
}
.add-btn {
  border: none;
  background: linear-gradient(90deg, #ff4da6, #ff85c1);
  color: #fff;
  box-shadow: 0 10px 20px rgba(255, 77, 166, 0.25);
  border-radius: 10px;
  font-size: 16px;
  padding: 0 24px;
  height: 42px;
}

.dept-stats {
  margin-bottom: 18px;
}
.stat-card {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #e6f7ff33;
  padding: 18px 16px;
  margin-bottom: 10px;
  min-height: 80px;
  gap: 16px;
}
.stat-icon {
  font-size: 32px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-right: 8px;
}
.stat-blue {
  background: linear-gradient(90deg, #e6f7ff, #f0faff);
  color: #1890ff;
}
.stat-green {
  background: linear-gradient(90deg, #e6ffed, #f6fffa);
  color: #52c41a;
}
.stat-red {
  background: linear-gradient(90deg, #fff1f0, #fff7f6);
  color: #ff4d4f;
}
.stat-yellow {
  background: linear-gradient(90deg, #fffbe6, #fffef6);
  color: #faad14;
}
.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #333;
}
.stat-label {
  color: #909399;
  font-size: 14px;
}

.dept-table-card {
  margin-top: 8px;
  border-radius: 12px;
  box-shadow: 0 2px 8px #e6f7ff33;
  background: #fff;
}
.table-header-flex {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #ff4da6;
  display: flex;
  align-items: center;
  gap: 6px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 0;
}
.dept-table {
  border-radius: 8px;
  overflow: hidden;
  font-size: 15px;
  background: #fff;
}
.dept-table-icon {
  color: #ff4da6;
  margin-right: 6px;
  font-size: 18px;
}
.dept-name {
  font-weight: 500;
  color: #333;
}
.pagination {
  margin-top: 18px;
  display: flex;
  justify-content: flex-end;
}
.dept-dialog :deep(.el-dialog__body) {
  padding-top: 24px;
}
.dept-form {
  padding: 0 8px;
}
.dialog-footer {
  text-align: right;
}
@media (max-width: 900px) {
  .dept-header,
  .table-header-flex {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .add-btn {
    width: 100%;
    margin-top: 8px;
  }
  .stat-card {
    margin-bottom: 10px;
  }
}
</style>
